let ENV = 'UAT'

let PATH = {
  'PROD': 'https://api.zgbbyy.com',
  'UAT': 'https://test-api.zgbbyy.com'
}

let CRYPT = {
  'PROD': true,
  'UAT':  false
}
let WEB_API = PATH[ENV]
let ISCRYPT = CRYPT[ENV]

let whiteList = ['/api/pay/pay/w/createPay']

// 创建axios实例
const request = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  baseURL: WEB_API,
  // 超时
  timeout: 50000,
})

// URL参数解析
const parse = (queryStr) => {
  const str = queryStr.replace(/^\?/, '')
  return str.split('&').reduce((pre, key) => {
    const [k, v] = key.split('=')
    pre[decodeURIComponent(k)] = decodeURIComponent(v)
    return pre
  }, {})
}

// 
var data = parse(location.search)

// request拦截器
request.interceptors.request.use(
  (config) => {
    // 携带token在请求头
    if (data.token) {
      config.headers['token'] = data.token
    }
    // 白名单中的接口不进行加密
    if (whiteList.includes(config.url)) {
      return config;
    }
    if (config.method === 'post') {
      config.headers['Content-Type'] = 'application/json'
      if (ISCRYPT) {
        config.data = {
          args: encrypt(JSON.stringify(config.data))
        }
      }
    }
    return config;
  },
  (error) => {
    console.log(error);
    Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(res => {
  console.log(res)
  // 白名单中的接口不进行加密
  if (whiteList.includes(res.config.url)) {
    return res.data
  }
  var decryptData = ISCRYPT ? JSON.parse(decrypt(res.data)) : res.data
  console.log(decryptData)
  if (decryptData.code !== 200) {
    vant.Toast(decryptData.message)
    return Promise.reject(decryptData)
  }
  vant.Toast.clear()
  return decryptData
}, err => {
  console.log(err)
  const error = err.response
  if (error.data.messagge) {
    vant.Toast(error.data.message)
  }
  return Promise.reject(error)
})